import React from 'react'
// import {Redirect ,Prompt} from 'react-router-dom'
import { Input, Table, Button, Tag, Tooltip, message, Space, Modal, Form, Select, Cascader, Upload } from 'antd';
import api from '../../until/index.js'
import '../../style/admin.css'
import Address from '../../until/address.js'
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons'
function getBase64(file) {
    console.log(file,'base64')
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
export default class Admin extends React.Component {
    formRef = React.createRef()
    constructor() {
        super()
        this.state = {
            flag: true,
            name: '',
            dataList: [],//商品数据
            colums: [{ title: '#', align: 'center', dataIndex: 'id', height: 60, key: 'id', render: (text, record, index) => `${index + 1}` },
            { title: '商品名称', align: 'center', width: 250, dataIndex: 'goodsname', key: 'goodsname' },
            { title: '商品图片', align: 'center', dataIndex: 'url', key: 'url', render: (text) => <img alt="" key="url" style={{ width: '60px', height: '60px' }} src={text.split(',')[0]} /> },
            { title: '价格', dataIndex: 'price', key: 'price', align: 'center' },
            {
                title: '适用人群', align: 'center', dataIndex: 'gender', key: 'gender', render: (text) => text == '0' ? <Tag color="green">男生</Tag> : <Tag color="red">女性</Tag> //eslint-disable-line 
            },
            { title: '库存', dataIndex: 'maxpeople', key: 'maxpeople', align: 'center', render: (t) => <div>{t ? t : '100'}件</div> },
            {
                title: '类型', align: 'center', dataIndex: 'type', key: 'type', render: (text) => <Tag color="green">{this.state.goods.map(item => {
                    return text == item.type ? item.name : '' //eslint-disable-line 
                })}</Tag>
            },
            {
                title: '操作', align: 'center', render: (text) => <div style={{ width: '100%', display: 'flex', justifyContent: 'space-evenly' }}><Tooltip placement="topLeft" title='修改'>
                    <Button icon={<EditOutlined />} size="small" type="primary" onClick={() => this.Update(text.id)}>修改</Button>
                </Tooltip> <Tooltip placement="topLeft" title="删除"><Button size="small" icon={<DeleteOutlined />} danger onClick={() => this.delete(text.id)}>删除</Button></Tooltip></div>
            }],
            goods: [],//商品类型
            Flag: false,//修改对话框
            goodsname: '',
            price: '',
            fileList: [],//商品大图
            fileList1:[],//商品详情图
            previewVisible: false,
            previewImage: '',
            previewTitle: '',
            opt:[{ value: 0, label: '男' }, { value: 1, label: '女' }],
            id:''
        }


    }

    //商品删除
    delete = (text) => {
        message.error('抱歉您没有权限')
    }
    //搜索事件
    onSearch = (v) => {
        console.log(v, '输入得值')
    }
    //修改事件
    Update = async(text) => {
        this.setState({
            Flag: !this.state.Flag,
            id:text
        })
     const data=await   api.getupdategoods({id:text})
        //  this.setState({
        //      goodsname:data.data.message[0].goodsname
        //  }) 
        var arr=[]
        var arrt=[]
        if(this.formRef.current){
            data.data.message[0].url.split(',').forEach((item,index)=>{
                if(item){
                    arr.push({url:item, name: 'image.png',
                    status: 'success',uid: index})
                }
            }) 
            data.data.message[0].banelurl.split(',').forEach((item,index)=>{
                if(item){
                    arrt.push({url:item, name: 'image.png',
                    status: 'success',uid: index})
                }
            }) 
            this.setState({
                fileList:arr,
                fileList1:arrt,
                goodsname: data.data.message[0].goodsname,
                type:data.data.message[0].type,
                price:data.data.message[0].price,
                gender:data.data.message[0].gender,
                maxpeople:data.data.message[0].maxpeople||100,
                address:data.data.message[0].address.split(','),
                status:data.data.message[0].status
            })
            this.formRef.current.setFieldsValue({
                  goodsname: data.data.message[0].goodsname,
                  type:data.data.message[0].type,
                  price:data.data.message[0].price,
                  gender:data.data.message[0].gender,
                  maxpeople:data.data.message[0].maxpeople||100,
                  address:data.data.message[0].address.split(',')
            })
        }
    }
    componentDidMount() {
        //数据列表请求
        api.getgoods({ type: 0 }).then(res => {
            this.setState({
                dataList: res.data.message
            })
        })
        //商品类型请求
        api.getgoodstype().then(res => {
            this.setState({
                goods: res.data.message
            })
        })
    }
    handleOk = () => {
        var url=''
        var banelurl=''
        if(!this.state.fileList||!this.state.fileList1){
            message.warning('请上传图片')
        }
        this.state.fileList.forEach(item=>{
            if(item.response){
                url+=item.response.data+','
               
            }else{
                url+=item.url+','
            }
        })
        this.state.fileList1.forEach(item=>{
            if(item.response){
                banelurl+=item.response.data+','
               
            }else{
                banelurl+=item.url+','
            }
        })
        let data={
            id:this.state.id,
            address:this.state.address,
            goodsname:this.state.goodsname,
            url,
            banelurl,
            type:this.state.type,
            gender:this.state.gender,
            price:this.state.price+'',
            maxpeople:this.state.maxpeople,
            status:this.state.status
        }
       this.formRef.current.validateFields().then(res=>{
          api.getUpdate(data).then(result=>{
            if(result.data.err_code =='1'){ //eslint-disable-line 
                this.setState({
                     Flag: !this.state.Flag
                })
                message.success('修改成功')
            }
        })
       });
        
    }

    handleCancel = () => {
        this.setState({
            Flag: !this.state.Flag
        })
    }
    //修改提交事件
    onFinish = () => {
    }
    onChange = (e) => {
        console.log(e)
        this.setState({
            [e.target.name]: e.target.value
        })

    }
    //商品类型选择
    handleChange = (text) => {
        this.setState({
            type: text
        })
    }
    //适用人群选择
    handleChanges = (text) => {
        this.setState({
            gender: text
        })
    }
    //发货地区
    handleSelectedPosition = (text) => {
        this.setState({
            address:text.join()
        })
    }
    //图片预览
    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    }
    //图片数组
    handleChangeImage = ({fileList}) => {
    //    var arr=[]
    //     if(data.file.response){
    //         arr.push({uid:this.state.fileList.length,status:'success',name:'image.png',url:data.file.response.data})
    //         this.setState({
    //            fileList:[...this.state.fileList,...arr]
    //         })
    //     }
        this.setState({fileList})
        //console.log(fileList)
    }
    handleChangeImage1=({fileList})=>{
        this.setState({fileList1:fileList})
    }
    handleCancelPer = () => this.setState({ previewVisible: false });
    render() {
        const { Search } = Input;
        const { colums, dataList, fileList,fileList1, previewVisible, previewImage, previewTitle,goodsname,opt } = this.state
        const options = []
        this.state.goods.forEach(item => {
            options.push({ value: item.type, label: item.name })
        })
       // console.log(this.state.fileList)
       // const opt = [{ value: 0, label: '男' }, { value: 1, label: '女' }]
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>上传图片</div>
            </div>
        )
        return (
            <div>
                <Space style={{ margin: '0 0 20rpx 0' }}>
                    <Search placeholder="请输入搜索id" allowClear onSearch={this.onSearch} enterButton />
                </Space>
                <Table columns={colums} dataSource={dataList} bordered bottomLeft rowKey={record => record.id}></Table>
                <Modal title="修改商品" width={1000} visible={this.state.Flag} onOk={this.handleOk} onCancel={this.handleCancel} footer={null} destroyOnClose={true}>
                    <Form onFinish={this.onFinish}   labelCol={{ span: 4 }} ref={this.formRef}
                        wrapperCol={{ span: 14 }}>
                        <Form.Item rules={[{ required: true, message: '请输入标题' }]} name="goodsname" label="商品标题">
                            <Input onChange={this.onChange} value={goodsname} allowClear></Input>
                        </Form.Item>
                        <Form.Item rules={[{ required: true, message: '请输入价格' }]} name="price" label="商品价格">
                            <Input type="number" name="price" onChange={this.onChange} ></Input>
                        </Form.Item>
                        <Form.Item rules={[{ required: true, message: '请输入库存' }]} name="maxpeople" label="商品库存">
                            <Input type="number" name="maxpeople" onChange={this.onChange} ></Input>
                        </Form.Item>
                        <Form.Item rules={[{ required: true, message: '请选择类型' }]} name="type" label="商品类型">
                            <Select options={options} onChange={this.handleChange} name="type"></Select>
                        </Form.Item>
                        <Form.Item rules={[{ required: true, message: '请选择适用人群' }]} name="gender" label="适用人群">
                            <Select options={opt} onChange={this.handleChanges} name="gender"></Select>
                        </Form.Item>
                        <Form.Item rules={[{ required: true, message: '请选择发货地区' }]} name="address" label="请选择发货地">
                            <Cascader options={Address} onChange={this.handleSelectedPosition} placeholder="请选发货地区"/>
                        </Form.Item>
                        <Form.Item rules={[{ required: false, message: '请上传商品大图' }]} name="url" label="商品主图">
                           <div>
                           <Upload action="https://dbyxs.xyz:8002/img" listType="picture-card" fileList={fileList} onPreview={this.handlePreview} onChange={this.handleChangeImage}>
                                {fileList.length >= 8 ? null : uploadButton}
                            </Upload>
                            <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={this.handleCancelPer}>
                                <img alt="example" style={{ width: '100%' }} src={previewImage} />
                            </Modal>
                           </div>
                        </Form.Item>
                        <Form.Item rules={[{ required: false, message: '请上传商品大图' }]} name="banelurl" label="商品详情图">
                           <div>
                           <Upload action="https://dbyxs.xyz:8002/img" listType="picture-card" fileList={fileList1} onPreview={this.handlePreview} onChange={this.handleChangeImage1}>
                                {fileList.length >= 8 ? null : uploadButton}
                            </Upload>
                            <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={this.handleCancelPer}>
                                <img alt="example" style={{ width: '100%' }} src={previewImage} />
                            </Modal>
                           </div>
                        </Form.Item>
                    </Form>
                    <div style={{ textAlign: "center" }}>
                        <Button onClick={this.handleOk} htmlType="submit" type="primary">提交</Button>
                        <Button onClick={this.handleCancel} danger style={{ marginLeft: 30 }}>删除</Button>
                    </div>

                </Modal>
            </div>
        )
    }
}